package com.objectcarpentry.kaylee.ui.handlers;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.handlers.HandlerUtil;

import com.objectcarpentry.kaylee.IPlayable;
import com.objectcarpentry.kaylee.IPlayer;
import com.objectcarpentry.kaylee.IPlaylist;
import com.objectcarpentry.kaylee.KayleePlugin;
import com.objectcarpentry.kaylee.ui.KayleeUIPlugin;
import com.objectcarpentry.kaylee.ui.views.LibraryView;
import com.objectcarpentry.kaylee.ui.views.TracklistView;

public class PlayHandler extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		
		
		IPlayer player = KayleePlugin.getDefault().getPlayer();
		IPlayable selection = null;
		
		ISelection s = HandlerUtil.getCurrentSelection(event);
		
		if (s instanceof IStructuredSelection){
			IStructuredSelection iss = (IStructuredSelection) s;
			Object o = iss.getFirstElement();
			if (o instanceof IPlayable){
				selection = (IPlayable) o;
			}
		}
		
		
		KayleeUIPlugin uiPlugin = KayleeUIPlugin.getDefault();
		String part_id = HandlerUtil.getActivePartId(event);
		if (TracklistView.ID.equals(part_id)){
			uiPlugin.getPlaylist().playOn(player, selection);
			uiPlugin.hookNavigationHandler(uiPlugin.getPlaylist());
		} else if (LibraryView.ID.equals(part_id)){
			if (selection != null){
				selection.playOn(player, null);
				uiPlugin.hookNavigationHandler((IPlaylist) selection);
			}
		}
		
		
		return null;
	}

	
	
}
